<template>
  <transition name="fade">
    <div v-if="isLoading" class="loading-overlay">
      <van-loading type="spinner" color="#1989fa" />
    </div>
  </transition>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import api from "@/api";
import { useAuthStore } from "@/stores/authStore";
import { trackEvent } from "@/utils/firebase";

const isLoading = ref(false);
const authStore = useAuthStore();

const router = useRouter();

// 谷歌登录
const loginGoogle = async () => {
  // 判断url上是否带code，带code就是从谷歌登录重定向回来的
  const url = new URL(window.location.href);
  const code = url.searchParams.get("code");
  if (code) {
    const params = {
      "code": code,
      "deviceId": localStorage.getItem("baseFingerprint")
    }
    try {
      const res = await api.googleLogin(params);
      isLoading.value = false
      // 更新状态
      authStore.user = res.data.name;
      authStore.token = res.data.token;
      authStore.eventType = res.data.eventType;
      authStore.lastLogin = new Date().toISOString();
      authStore.isrealLogin = true;//真实用户登录；
      // 持久化存储
      localStorage.setItem("token", res.data.token);
      //判断是谷歌登录，还是谷歌注册登录
      trackEvent("登录成功", { id: "100063", type: res.data.eventType }); //埋点
      router.push("/");
      return true;
    } catch (error) {
      isLoading.value = false
      console.error(error);
      throw error;
    }
  }
};

onMounted(() => {
  isLoading.value = true
  loginGoogle()
});
</script>

<style scoped>
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.8);
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}
</style>
